package com.dahua.messagesyncsh.util;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class GsonUtils {
    public static Gson getGson() {
        return new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
            @Override
            public LocalDateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
                String dateTime = jsonElement.getAsJsonPrimitive().getAsString();
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
                try {
                    return LocalDateTime.parse(dateTime, dateTimeFormatter);
                } catch (DateTimeParseException e) {
                    throw new RuntimeException(e);
                }
            }
        }).registerTypeAdapter(Timestamp.class, new JsonDeserializer<Timestamp>() {
            @Override
            public Timestamp deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
                JsonPrimitive asJsonPrimitive = jsonElement.getAsJsonPrimitive();
                if (asJsonPrimitive.isNumber()) {
                    long millis = asJsonPrimitive.getAsLong();
                    return new Timestamp(millis);
                } else if (asJsonPrimitive.isString()) {
                    String srcString = asJsonPrimitive.getAsString();
                    return Timestamp.valueOf(srcString);
                }
                throw new IllegalArgumentException("illegal type");
            }
        }).create();
    }
}
